package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Slf4j
@Component
public class CacheClient {

    @Autowired
    private StringRedisTemplate redisTemplate;
    private final static ExecutorService EXECUTORTreedPOOL = Executors.newFixedThreadPool(10);

    public CacheClient() {
    }

    public CacheClient(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    /**
     * 互斥锁结果缓存击穿
     * @param id
     * @return
     */
    public <T,ID> T queryWithMutex(String lockPrefix,String cachePrefix,Long TTL,TimeUnit timeUnit,ID id,Class<T> tClass,Function<ID,T> function){
        String key  = cachePrefix + id;
        //从redis 查询缓存
        String json = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)){
            log.info("缓存中存在直接返回！");
            //存在直接返回
            T cacheObject = JSONUtil.toBean(json, tClass);
            return cacheObject;
        }
        if (json != null){//缓存的为空值
            return null;
        }
        T cacheObject = null;
        //不存在从数据库查询
        //获取互斥锁
        String lock = lockPrefix + id;
        try {
            boolean isLock = tryLock(lock);
            if (!isLock){
                //没有获取到锁
                Thread.sleep(50);
                //4.3 失败，则休眠重试
                return queryWithMutex(lockPrefix,cachePrefix,TTL,timeUnit,id,tClass,function);
            }
            //获取到了锁 查询数据库
            log.info("redis中不存在 查询数据库");
            T newR = function.apply(id);
            //不存在返回错误
            if (newR == null){
                //使用缓存空值解决 缓存穿透
                redisTemplate.opsForValue().set(cachePrefix + id,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.SECONDS);
                return null;
            }

            //存在 存入redis 返回
            redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(newR),TTL, timeUnit);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unlock(lock);
        }
        return cacheObject;
    }

    /**
     * 缓存穿透
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @param <R>
     * @param <ID>
     * @return
     */

    public <R,ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit){
        String key = keyPrefix + id;
        // 1.从redis查询商铺缓存
        String json = redisTemplate.opsForValue().get(key);
        // 2.判断是否存在
        if (StrUtil.isNotBlank(json)) {
            // 3.存在，直接返回
            return JSONUtil.toBean(json, type);
        }
        // 判断命中的是否是空值
        if (json != null) {
            // 返回一个错误信息
            return null;
        }

        // 4.不存在，根据id查询数据库
        R r = dbFallback.apply(id);
        // 5.不存在，返回错误
        if (r == null) {
            // 将空值写入redis
            redisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            // 返回错误信息
            return null;
        }
        // 6.存在，写入redis
        this.set(key, r, time, unit);
        return r;
    }
    public void set(String key, Object value, Long time, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }


    public <T,ID> void save2RedisData(ID id,Long expireTime,Function<ID, T> function){
        //缓存预热
        T shop = function.apply(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));

    }

    /**
     * 逻辑时间 缓存击穿
     * @param <T>
     * @param id
     * @param tClass
     * @return
     */
    public <T,ID> T queryWithLogicalExpire(String lockPrefix, String keyPrefix, ID id, Class<T> tClass,Function<ID, T> function,Long expireTime,TimeUnit timeUnit) {
        String key = keyPrefix + id;

        log.info("cacheKey = {}",key);
    //    String key = RedisConstants.CACHE_SHOP_KEY + id;
        //从缓存中查询数据
        String json = redisTemplate.opsForValue().get(key);
        //如果没有缓存 直接返回null
        if (StrUtil.isBlank(json)){
            log.info("redis中没有提前进行缓存预热 直接返回null ");
            return null;
//            T shop = function.apply(id);
//            if (shop == null){
//                log.info("redis中没有缓存该店铺，数据库中也没存在该店铺 ");
//                return null;
//            }
//            log.info("redis中没有缓存该店铺，但是数据库中存在该店铺 ");
//            setWithLogicalExpire(key,shop,expireTime,timeUnit);
//            return shop;
        }
        //转换成对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        T cacheObject = JSONUtil.toBean((JSONObject) redisData.getData(), tClass);
        //判断缓存是否过期
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())){
            //没有过期
            log.info("缓存没有过期 直接返回");
            return cacheObject;
        }
        //已经过期了 进行缓存重建
        //获取互斥锁
        String lockKey = lockPrefix + key;
        boolean lock = tryLock(lockKey);
        if (lock){//拿到锁
            //开启新的线程
            EXECUTORTreedPOOL.submit(()->{
                log.info("进行缓存重建...");
                //进行重建
                try {
                    //newR   getById
                    T newR = function.apply(id);
                    setWithLogicalExpire(key,newR,expireTime,timeUnit);
                } catch (Exception e) {
                    // e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {//释放锁
                    unlock(lockKey);
                }
            });
        }
        return cacheObject;
    }
    private boolean tryLock(String key) {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        redisTemplate.delete(key);
    }

    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        // 设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        // 写入Redis
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }
}
